package com.schillerchina.baselibrary.network.factory;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author zhangzhiguo
 * @date 2019-08-05 09:39
 * @Description: 网络请求GSON解析 产品类
 */

public class EncryptGsonResponseConverter<T>
        implements Converter<ResponseBody, T> {
    private final TypeAdapter<T> adapter;
    private final Gson gson;

    private static final String TAG = "Response";

    EncryptGsonResponseConverter(Gson gson, TypeAdapter<T> typeAdapter) {
        this.gson = gson;
        this.adapter = typeAdapter;
    }

    public T convert(ResponseBody responseBody)
            throws IOException {
        String response = responseBody.string();
        Log.i(TAG, "response: " + response);

        InputStream inputStream = new ByteArrayInputStream(response.getBytes());
        Reader reader = new InputStreamReader(inputStream);
        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            return adapter.read(jsonReader);
        } finally {
            responseBody.close();
        }
    }
}
